<template>
  <div class="app-container">
    <transition :enter-active-class="animate.searchAnimate.enter" :leave-active-class="animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="商户名称" prop="account" v-if="isAdmin">
              <el-input v-model="queryParams.createName" placeholder="请输入商户名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="邮箱账号" prop="account">
              <el-input v-model="queryParams.account" placeholder="请输入邮箱账号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="协议" prop="agreement">
              <el-select v-model="queryParams.agreement" placeholder="请选择服务器协议" clearable>
                <el-option v-for="dict in email_agreement" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="端口" prop="port">
              <el-input v-model="queryParams.port" placeholder="请输入端口" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-tooltip :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailAccount:add']" type="primary" plain icon="Plus" size="mini" @click="handleAdd">新增 </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['system:EmailAccount:edit']"
                type="success"
                plain
                icon="Edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['system:EmailAccount:remove']"
                type="danger"
                plain
                icon="Delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                >删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailAccount:export']" type="warning" plain icon="Download" size="mini" @click="handleExport"
                >导出
              </el-button>
            </el-col>
          </el-row>
          <div class="flex items-center w-fit gap-5">
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :page-sizes="[20, 50, 100, 300]"
              :total="total"
              style="height: 30px; margin: 0; padding: 0 !important"
              @pagination="getList"
            />
            <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="EmailAccountList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="商户名称" v-if="isAdmin" align="center" prop="createName" />
        <el-table-column label="邮箱账号" align="center" prop="account" />
        <el-table-column label="邮箱密码" align="center" prop="password" />
        <el-table-column label="服务器协议" align="center" prop="agreement">
          <template #default="scope">
            <dict-tag :options="email_agreement" :value="scope.row.agreement" />
          </template>
        </el-table-column>
        <el-table-column label="服务器地址" align="center" prop="server" />
        <el-table-column label="端口" align="center" prop="port" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="email_account_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-hasPermi="['system:EmailAccount:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              >修改
            </el-button>
            <el-button v-hasPermi="['system:EmailAccount:remove']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-5 mr-[-0.5rem]">
        <div class="flex justify-end items-center w-fit gap-5">
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 300]"
            :total="total"
            style="height: 30px; margin: 0; padding: 0 !important"
            @pagination="getList"
          />
          <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
        </div>
      </div>
    </el-card>

    <!-- 添加或修改邮箱账号对话框 -->
    <el-dialog v-model="open" :title="title" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="邮箱账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入邮箱账号" />
        </el-form-item>
        <el-form-item label="邮箱密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入邮箱密码" />
        </el-form-item>
        <el-form-item label="服务器协议" prop="agreement">
          <el-select v-model="form.agreement" placeholder="请选择服务器协议">
            <el-option v-for="dict in email_agreement" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务器地址" prop="server">
          <el-input v-model="form.server" placeholder="请输入服务器地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入端口" />
        </el-form-item>
        <el-form-item v-if="form.id" label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in email_account_status" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用SSL" prop="enableSsl">
          <el-switch v-model="form.enableSsl" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listEmailAccount, getEmailAccount, delEmailAccount, addEmailAccount, updateEmailAccount } from '@/api/email/EmailAccount';
import useUserStore from '@/store/modules/user';
export default {
  name: 'EmailAccount',
  data() {
    return {
      showSearch: false,
      email_agreement: [],
      email_account_status: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 邮箱账号表格数据
      EmailAccountList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        account: null,
        password: null,
        agreement: null,
        server: null,
        port: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        account: [{ required: true, message: '邮箱账号不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '邮箱密码不能为空', trigger: 'blur' }],
        agreement: [{ required: true, message: '服务器协议不能为空', trigger: 'change' }],
        server: [{ required: true, message: '服务器地址不能为空', trigger: 'blur' }],
        port: [{ required: true, message: '端口不能为空', trigger: 'blur' }]
      }
    };
  },
  async created() {
    let res = await this.useDict('email_agreement', 'email_account_status');
    await this.getList();
    setTimeout(() => {
      this.email_agreement = res.email_agreement;
      this.email_account_status = res.email_account_status;
    }, 1000);
  },
  computed: {
    isAdmin() {
      const { isAdmin } = useUserStore();
      return isAdmin;
    }
  },
  methods: {
    /** 查询邮箱账号列表 */
    getList() {
      this.loading = true;
      listEmailAccount(this.queryParams).then((response) => {
        this.EmailAccountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        account: null,
        password: null,
        agreement: null,
        server: null,
        port: null,
        isDelete: null,
        deptId: null,
        createId: null,
        createName: null,
        createTime: null,
        updateId: null,
        updateName: null,
        updateTime: null
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加邮箱账号';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getEmailAccount(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = '修改邮箱账号';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateEmailAccount(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addEmailAccount(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除邮箱账号编号为"' + ids + '"的数据项？')
        .then(function () {
          return delEmailAccount(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/EmailAccount/export',
        {
          ...this.queryParams
        },
        `EmailAccount_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
<style scoped>
.gn-status {
  color: #1ab394;
}
</style>
